import { ref } from 'vue';
import { defineStore } from 'pinia';
import { getStorage, setStorage, removeStore } from '@/utils/storage';
import router from '@/router/index';

interface UserInfo {
  avatar: string;
  nickName: string;
}

interface LoginParams {
  username: string;
  password: string;
}

const defaultUserInfo: UserInfo = {
  avatar: '',
  nickName: '测试'
};

export const useUser = defineStore('user', () => {
  const token = ref<string>(getStorage({ key: 'test-token', islocal: true }) || '');
  const userinfo = ref<UserInfo>(getStorage({ key: 'userinfo', islocal: true }) || defaultUserInfo);

  async function login(params: LoginParams) {
    try {
      // 这里可以添加实际的登录API调用
      token.value =
        'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjMxMTE0NGFkLTI1OTAtNDQwMy1iYWMxLWY5MTQ2NmQ2NjAxNSJ9.gurW9o6PTuoaOUJkt1IJpsGlfPW0hanTKqz96cnjXhzUG6Qc4ydiNaaFDl7fTuuwJFsQOcSy2xiVdSZON6iwKg';
      setStorage({
        key: 'test-token',
        value: token.value,
        islocal: true
      });
      await getUserInfo();
    } catch (error) {
      console.error('登录失败:', error);
      throw error;
    }
  }

  async function getUserInfo() {
    try {
      // 这里可以添加获取用户信息的API调用
      userinfo.value = defaultUserInfo;
      setStorage({ key: 'userinfo', value: userinfo.value, islocal: true });
      await router.push('/');
    } catch (error) {
      console.error('获取用户信息失败:', error);
      throw error;
    }
  }

  function logout() {
    token.value = '';
    userinfo.value = defaultUserInfo;
    removeStore({ key: 'test-token', islocal: true });
    removeStore({ key: 'userinfo', islocal: true });
    router.push('/login');
  }

  return {
    userinfo,
    token,
    login,
    logout
  };
});
